var carousel = document.querySelector("ul"),
	left_arrow = document.querySelector(".left_arrow"),
	right_arrow = document.querySelector(".right_arrow"),
	controls = document.querySelectorAll("ol li"),
	now_index = 0,
	last_index = 0,
	lis = document.querySelector("ul li"),
	is_run = false;
//右箭头点击事件
right_arrow.addEventListener("click", function() {
	if(!is_run) {
		is_run = true;
		++now_index >= 5 ? now_index = 0 : "";
		run(now_index);
	}
})
//左箭头点击事件
left_arrow.addEventListener("click", function() {
	if(!is_run) {
		is_run = true;
		--now_index < 0 ? now_index = 4 : "";
		run(now_index);
	}

});

//事件代理--圆点控制
//document.querySelector("ol").addEventListener("mouseover",function(e){	
//		for (var i=0;i<=controls.length;i++) {
//			if (e.target==controls[i]) {
//				console.log(i);
//				run(i);
//			}
//		}
//})

//圆点控制--index
//for(var i = 0; i < controls.length; i++) {
//	controls[i].index=i;
//	controls[i].addEventListener("mouseover", function() {
//		run(i);
//	});
//}

//圆点控制--闭包

for(var i = 0; i < controls.length; i++) {
	(function(j) {
		controls[j].addEventListener("mouseover", function() {
			run(j);
		});
	})(i);
}

//控制圆点--自定义属性
//for(var i = 0; i < controls.length; i++) {
//	controls[i].setAttribute("data-index",i)
//	controls[i].addEventListener("mouseover", function() {
//		console.log(this.getAttribute("data-index"));
//		run(this.getAttribute("data-index"));
//	});
//}

//轮播图运行主函数
function run(target_index) {
	carousel.style.transform = "translateX(-" + target_index * 100 + "%)";
	controls[last_index].classList.remove("active");
	last_index = target_index;
	controls[target_index].classList.add("active");
	carousel.addEventListener("transitionend", function() {
		is_run = false;
	})
};
//
function timer() {
	set_time = setInterval(function() {
		++now_index >= 5 ? now_index = 0 : "";
		carousel.style.transform = "translateX(-" + now_index * 100 + "%)";
		controls[last_index].classList.remove("active");
		last_index = now_index;
		controls[now_index].classList.add("active");
	}, 2000);
};
timer();

carousel.addEventListener("mouseover",function(){
	clearInterval(set_time);
});
carousel.addEventListener("mouseleave",function(){
	timer();
})
